Java 执行Linux Command

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
 
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


@RestController
public class ExecuteController {
/**
* 执行指定命令
*/
@RequestMapping(value = "/executeMult", method = RequestMethod.GET)
public Object executeMult(String command) throws IOException {
if (StringUtils.isEmpty(command))
return "Error Command ";
String[] strings = new String[3];
strings[0] = "/bin/sh";
strings[1] = "-c";
strings[2] = command;
StringBuffer stringBuffer = new StringBuffer();
int exitValue = -1;
BufferedReader bufferedReader = null;
try {
// command process
Process process = Runtime.getRuntime().exec(strings);
BufferedInputStream bufferedInputStream = new BufferedInputStream(process.getInputStream());
bufferedReader = new BufferedReader(new InputStreamReader(bufferedInputStream));
// command log
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append(System.getProperty("line.separator"));
System.out.println(line);
}
// command exit
process.waitFor();
exitValue = process.exitValue();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bufferedReader != null) {
bufferedReader.close();
}
}
if (exitValue == 0) {
return stringBuffer.toString();
} else {
return "command exit value(" + exitValue + ") is failed";
}
}
}